package com.houduan.dao;

import com.houduan.model.Order;
import com.houduan.model.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class OrderDao {

    private static final String URL = "jdbc:mysql://localhost:3306/netbar";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "rjxy123456";

    private static final String INSERT_ORDER_SQL = "INSERT INTO orders (user_id, amount, status, create_time) VALUES (?, ?, ?, ?)";
    private static final String SELECT_ORDER_BY_ID = "SELECT * FROM orders WHERE order_id = ?";
    private static final String SELECT_ORDERS_BY_USERNAME = "SELECT o.* FROM orders o INNER JOIN users u ON o.user_id = u.id WHERE u.username LIKE ? ORDER BY o.create_time DESC";
    private static final String SELECT_ALL_ORDERS = "SELECT * FROM orders ORDER BY create_time DESC";
    private static final String DELETE_ORDER_SQL = "DELETE FROM orders WHERE order_id = ?";
    private static final String UPDATE_ORDER_SQL = "UPDATE orders SET amount = ?, status = ? WHERE order_id = ?";
    private static final String UPDATE_USER_BALANCE_SQL = "UPDATE users SET balance = balance + ? WHERE id = ?";

    // 获取数据库连接
    private Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL, USERNAME, PASSWORD);
    }

    // 添加订单
    public void addOrder(Order order) {
        try (Connection connection = getConnection();
             PreparedStatement orderStatement = connection.prepareStatement(INSERT_ORDER_SQL);
             PreparedStatement userBalanceStatement = connection.prepareStatement(UPDATE_USER_BALANCE_SQL)) {

            // 插入订单
            orderStatement.setInt(1, order.getUser().getId());
            orderStatement.setDouble(2, order.getAmount());
            orderStatement.setString(3, order.getStatus());
            orderStatement.setTimestamp(4, new Timestamp(order.getCreateTime().getTime()));
            orderStatement.executeUpdate();

            // 如果订单状态为已支付，更新用户余额
            if ("已支付".equals(order.getStatus())) {
                userBalanceStatement.setDouble(1, order.getAmount());
                userBalanceStatement.setInt(2, order.getUser().getId());
                userBalanceStatement.executeUpdate();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 根据订单 ID 获取订单
    public Order getOrderById(int orderId) {
        Order order = null;
        try (Connection connection = getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(SELECT_ORDER_BY_ID)) {
            preparedStatement.setInt(1, orderId);
            try (ResultSet resultSet = preparedStatement.executeQuery()) {
                if (resultSet.next()) {
                    int userId = resultSet.getInt("user_id");
                    double amount = resultSet.getDouble("amount");
                    String status = resultSet.getString("status");
                    Timestamp createTime = resultSet.getTimestamp("create_time");

                    User user = new UserDao().getUserById(userId); // 调用 UserDao 获取用户信息
                    order = new Order(orderId, user, amount, status, createTime);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return order;
    }

    // 根据用户名获取订单（支持模糊查询）
    public List<Order> getOrdersByUsername(String username) {
        List<Order> orders = new ArrayList<>();
        try (Connection connection = getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(SELECT_ORDERS_BY_USERNAME)) {
            preparedStatement.setString(1, "%" + username + "%");
            try (ResultSet resultSet = preparedStatement.executeQuery()) {
                while (resultSet.next()) {
                    int orderId = resultSet.getInt("order_id");
                    int userId = resultSet.getInt("user_id");
                    double amount = resultSet.getDouble("amount");
                    String status = resultSet.getString("status");
                    Timestamp createTime = resultSet.getTimestamp("create_time");

                    User user = new UserDao().getUserById(userId); // 调用 UserDao 获取用户信息
                    Order order = new Order(orderId, user, amount, status, createTime);
                    orders.add(order);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return orders;
    }

    // 获取所有订单（按创建时间降序）
    public List<Order> getAllOrders() {
        List<Order> orders = new ArrayList<>();
        try (Connection connection = getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(SELECT_ALL_ORDERS);
             ResultSet resultSet = preparedStatement.executeQuery()) {
            while (resultSet.next()) {
                int orderId = resultSet.getInt("order_id");
                int userId = resultSet.getInt("user_id");
                double amount = resultSet.getDouble("amount");
                String status = resultSet.getString("status");
                Timestamp createTime = resultSet.getTimestamp("create_time");

                User user = new UserDao().getUserById(userId); // 调用 UserDao 获取用户信息
                Order order = new Order(orderId, user, amount, status, createTime);
                orders.add(order);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return orders;
    }

    // 删除订单
    public void deleteOrder(int orderId) {
        try (Connection connection = getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(DELETE_ORDER_SQL)) {
            preparedStatement.setInt(1, orderId);
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 更新订单
    public void updateOrder(Order order) {
        try (Connection connection = getConnection();
             PreparedStatement orderStatement = connection.prepareStatement(UPDATE_ORDER_SQL);
             PreparedStatement userBalanceStatement = connection.prepareStatement(UPDATE_USER_BALANCE_SQL)) {

            // 检查订单当前状态
            Order existingOrder = getOrderById(order.getOrderId());
            if (existingOrder == null) {
                throw new SQLException("订单不存在");
            }

            // 更新订单信息
            orderStatement.setDouble(1, order.getAmount());
            orderStatement.setString(2, order.getStatus());
            orderStatement.setInt(3, order.getOrderId());
            orderStatement.executeUpdate();

            // 如果状态从未支付变为已支付，更新用户余额
            if ("未支付".equals(existingOrder.getStatus()) && "已支付".equals(order.getStatus())) {
                userBalanceStatement.setDouble(1, order.getAmount());
                userBalanceStatement.setInt(2, order.getUser().getId());
                userBalanceStatement.executeUpdate();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
